import cv2
import numpy as np
import matplotlib.pyplot as plt
import math


def Rotate(rawImage, angle):
	height, width = rawImage.shape
	resultImage = np.zeros((height, width), np.uint8)
	anglePi = angle*math.pi/180.0
	cosA = math.cos(anglePi)
	sinA = math.sin(anglePi)
	for i in range(height):
		for j in range(width):
			x = int(cosA*i-sinA*j-0.5*width*cosA+0.5*height*sinA+0.5*width)
			y = int(sinA*i+cosA*j-0.5*width*sinA-0.5*height*cosA+0.5*height)
			if x>-1 and x<height and y>-1 and y<width:
				resultImage[x,y] = rawImage[i,j]

	return resultImage


def Zoom(image,m,n):
	height, width = image.shape
	H = int(height*m)
	W = int(width*n)
	size = (H, W)
	iZoom = np.zeros((height, width), np.uint8)
	for i in range(H):
		for j in range(W):
			x = int(i/m)
			y = int(j/n)
			iZoom[i,j] = image[x,y]
	return iZoom


def Reduce(image,m,n):
	height, width = image.shape
	H = int(image.height*m)
	W = int(image.width*n)
	size = (H, W)
	iReduce = np.zeros((height, width), np.uint8)
	for i in range(H):
		for j in range(W):
			x = int(i/m)
			y = int(j/n)
			iReduce[i,j] = image[x,y]
	return iReduce

def JReduce(image,m,n):
	height, width = image.shape
	H = int(height*m)
	W = int(width*n)
	size = (H, W)
	iJReduce = np.zeros((height, width), np.uint8)
	for i in range(H):
		for j in range(W):
			x1 = int(i/m)
			x2 = int((i+1)/m)
			y1 = int(j/n)
			y2 = int((j+1)/n)
			sum = [0,0,0]
			for k in range(x1,x2):
				for l in range(y1,y2):
					sum[0] = sum[0]+image[k,l][0]
					sum[1] = sum[1]+image[k,l][1]
					sum[2] = sum[2]+image[k,l][2]
			num = (x2-x1)*(y2-y1)
			iJReduce[i,j] = (sum[0]/num,sum[1]/num,sum[2]/num)
	return iJReduce



def Translate(rawImage, height, width):
	pass



if __name__ == '__main__':
	rawImg = cv2.imread('./img/fig3.tif', cv2.CV_LOAD_IMAGE_GRAYSCALE)
	cv2.namedWindow('Original Image', cv2.CV_WINDOW_AUTOSIZE)
	cv2.imshow( "Original Image", rawImg)

	resultImage = Rotate(rawImg, 45)
	cv2.namedWindow('Rotated Image', cv2.CV_WINDOW_AUTOSIZE)
	cv2.imshow( "Rotated Image", resultImage)

	zoomImage = Zoom(rawImg,3,3)
	cv2.namedWindow('Enlarged Image', cv2.CV_WINDOW_AUTOSIZE)
	cv2.imshow( "Enlarged Image", zoomImage)

	cv2.waitKey(0)
	cv2.destroyAllWindows()